<?php

/**
 * This is the model class for table "category".
 *
 * The followings are the available columns in table 'category':
 * @property integer $id
 * @property integer $parent_id
 * @property string $created_at
 * @property string $updated_at
 */
class Category extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Category the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'category';
    }

    public $hasParent = false;

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('parent_id, is_displayed', 'numerical', 'integerOnly' => true),
            array('hasParent', 'boolean'),
            array('created_at, updated_at', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, parent_id, created_at, updated_at', 'safe', 'on' => 'search'),
        );
    }

    /**
     * set timestamp before save
     */
    public function beforeSave() {
        if ($this->isNewRecord)
            $this->created_at = new CDbExpression('NOW()');
        $this->updated_at = new CDbExpression('NOW()');
        return parent::beforeSave();
    }

    /**
     *  delete all category detail
     */
    public function beforeDelete() {
        $this->setNullCategoryIdProducts();
        CategoryDetail::model()->deleteCategoryDetailsByCategoryID($this->id);
        return parent::beforeDelete();
    }

    /**
     * set null category_id for products
     */
    public function setNullCategoryIdProducts() {
        $products = $this->products;
        foreach ($products as $product) {
            $product->category_id = '';
            $product->status = 'no';
            $product->update();
        }
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'parent' => array(self::BELONGS_TO, 'Category', 'parent_id'),
            'childs' => array(self::HAS_MANY, 'Category', 'parent_id'),
            'categoryDetails' => array(self::HAS_MANY, 'CategoryDetail', 'category_id'),
            'products' => array(self::HAS_MANY, 'Product', 'category_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {

        return array(
            'id' => Yii::t('category', 'id'),
            'parent_id' => Yii::t('category', 'Category Type'),
            'hasParent' => Yii::t('category', 'Has Parent'),
            'created_at' => Yii::t('category', 'Created At'),
            'updated_at' => Yii::t('category', 'Updated At'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        // $criteria->condition = "parent_id is not null";
        $criteria->compare('id', $this->id);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => Constant::PAGE_SIZE,),
        ));
    }

    /**
     * Get category type( have 2 type)
     */
    public function getAllCategories($language, $hasParent = TRUE, $isDisplayed = FALSE) {
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'categoryDetails' => array('select' => array('name')),
        );
        $criteria->condition = "categoryDetails.language =:language";
        if ($hasParent) {
            $criteria->addCondition('parent_id is not null');
        }
        if ($isDisplayed) {
            $criteria->condition = "is_displayed = 1";
        }
        $criteria->params = array(':language' => $language);

        $categories = Category::model()->findAll($criteria);

        $categoryTypes = array();
        foreach ($categories as $category) {
            $categoryDetails = $category->categoryDetails;
            $parentType = array();
            $parentType["id"] = $category->id;
            $parentType["name"] = $categoryDetails[0]->name;
            $categoryTypes[$category->id] = $parentType;
        }
        return $categoryTypes;
    }

    /**
     * Get category of product, 
     * @var $type : 
     */
    public function getCategoriesByType($language, $type, $hasParent = TRUE, $isDisplayed = FALSE) {
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'categoryDetails' => array('select' => array('name')),
        );

        $criteria->condition = "categoryDetails.language =:language";
        $criteria->condition = "parent_id=:type";
        if ($hasParent) {
            $criteria->addCondition('parent_id is not null');
        }
        if ($isDisplayed) {
            $criteria->condition = "is_displayed = 1";
        }
        $criteria->params = array(':language' => $language, ':type' => $type);

        $categories = Category::model()->findAll($criteria);
        $categoryTypes = array();
        foreach ($categories as $category) {
            $categoryDetails = $category->categoryDetails;
            $parentType = array();
            $parentType["id"] = $category->id;
            $parentType["name"] = $categoryDetails[0]->name;
            $categoryTypes[$category->id] = $parentType;
        }
        return $categoryTypes;
    }

    /**
     * Get category 
     */
    public function getCategories($language = "en", $isDisplayed = FALSE) {
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'categoryDetails' => array('select' => array('name')),
        );

        $criteria->condition = "categoryDetails.language =:language";
        if ($isDisplayed) {
            $criteria->condition = "is_displayed = 1";
        }
        $criteria->params = array(':language' => $language);
        $categories = Category::model()->findAll($criteria);

        $categoryTypes = array();
        foreach ($categories as $category) {
            $categoryDetails = $category->categoryDetails;
            $categoryArray = array();
            $categoryArray["id"] = $category->id;
            $categoryArray["name"] = $categoryDetails[0]->name;
            $categoryTypes[$category->id] = $categoryArray;
        }
        return $categoryTypes;
    }

    /**
     * Get product, 
     * @var $type : product is 1, equipment is 2
     */
    public function getProducts($language, $type, $hasParent = TRUE, $isDisplayed = FALSE) {
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'categoryDetails' => array('select' => array('name')),
        );

        $criteria->condition = "categoryDetails.language =:language";
        $criteria->addCondition('parent_id=:type');
        if ($hasParent) {
            $criteria->addCondition('parent_id is not null');
        }
        if ($isDisplayed) {
            $criteria->condition = "is_displayed = 1";
        }
        $criteria->params = array(':type' => $type, ':language' => $language);
        $categories = Category::model()->findAll($criteria);
        
        $products = array();
        foreach ($categories as $category) {
            $productTemps = $category->products;
            foreach ($productTemps as $productTemp) {
                $products[] = $productTemp;
            }
        }
        return $products;
    }

    /**
     * get category parent
     */
    public function getCategoryParent($name) {
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'categoryDetails',
        );
        $criteria->condition = "categoryDetails.name =:name";
        $criteria->addCondition('parent_id is null');
        $criteria->params = array(':name' => $name);
        $categories = Category::model()->findAll($criteria);
        $category = new Category;
        if (count($categories) > 0) {
            $category = $categories[0];
        }
        return $category;
    }

    /**
     * get name of category by id
     */
    public function getCategoryNameById($id) {
        $name = null;
        if ($id != null) {
            $category = Category::model()->findByPk($id);
            if ($category != null) {
                $language = Yii::app()->session['language'];
                if (!isset($language)) {
                    $language = 'en';
                }
                $categoryDetails = $category->categoryDetails;
                foreach ($categoryDetails as $categoryDetail) {
                    if ($categoryDetail->language == $language) {
                        $name = $categoryDetail->name;
                    }
                }
            }
        }
        return $name;
    }

    /**
     * get category detail and cast corresponding 
     */
    public function getCategoryDetail($language = 'en') {
        $result = null;
        $categoryDetails = $this->categoryDetails;
        foreach ($categoryDetails as $categoryDetail) {
            if ($categoryDetail->language == $language) {
                $result = $categoryDetail;
            }
        }
        return $result;
    }

    public function categoryDetail() {
        $language = Yii::app()->session['language'];
        if (!isset($language)) {
            $language = 'en';
        }
        return $this->getCategoryDetail($language);
    }

}

